import React, { useState, useEffect } from 'react';
import {
    Button,
    Space,
    Tag,
    Modal,
    Form,
    message,
    Dropdown,
    Typography,
    Tooltip,
    Popconfirm,
    Switch
} from 'antd';
import {
    SearchOutlined,
    DeleteOutlined,
    EyeOutlined,
    MoreOutlined,
    MessageOutlined,
    FileImageOutlined,
    FileOutlined,
    AudioOutlined,
    UserOutlined,
    SmileOutlined,
    SettingOutlined,
    ClearOutlined,
    CheckOutlined,
    CloseOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { MenuProps } from 'antd';
import dayjs from 'dayjs';
import * as chatService from '@/services/chat';
import type {
    ChatRecord,
    ChatQueryParams,
    ChatApiResponse
} from '@/types';
import { SearchForm, DataTable } from '@/components';
import type { SearchFieldConfig, PaginationConfig, ToolbarAction, BatchAction } from '@/components';

const { Text, Paragraph } = Typography;

// 消息类型配置
const MESSAGE_TYPES = {
    user: { color: 'blue', text: '用户', icon: <UserOutlined /> },
    customer_service: { color: 'green', text: '管理员', icon: <SettingOutlined /> },
};

// 已读状态配置
const READ_STATUS = {
    true: { color: 'green', text: '已读' },
    false: { color: 'orange', text: '未读' },
};

const NormalChatPage: React.FC = () => {
    const [loading, setLoading] = useState(false);
    const [records, setRecords] = useState<ChatRecord[]>([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [pagination, setPagination] = useState<PaginationConfig>({
        current: 1,
        pageSize: 20,
        total: 0,
    });

    // 搜索相关
    const [searchForm] = Form.useForm();
    const [searchParams, setSearchParams] = useState<ChatQueryParams>({});

    // 模态框状态
    const [detailModalVisible, setDetailModalVisible] = useState(false);
    const [roomModalVisible, setRoomModalVisible] = useState(false);
    const [currentRecord, setCurrentRecord] = useState<ChatRecord | null>(null);
    const [roomRecords, setRoomRecords] = useState<ChatRecord[]>([]);

    // 搜索字段配置
    const searchFields: SearchFieldConfig[] = [
        {
            name: 'keyword',
            type: 'input',
            placeholder: '搜索消息内容',
            width: 200,
            prefix: <SearchOutlined />
        },
        {
            name: 'user_id',
            type: 'input',
            placeholder: '用户ID',
            width: 120
        },
        {
            name: 'room_id',
            type: 'input',
            placeholder: '房间ID',
            width: 160
        },
        {
            name: 'message_type',
            type: 'select',
            placeholder: '选择发送者',
            width: 120,
            options: [
                { label: '用户', value: 'user' },
                { label: '管理员', value: 'customer_service' }
            ]
        },
        {
            name: 'is_read',
            type: 'select',
            placeholder: '阅读状态',
            width: 120,
            options: [
                { label: '已读', value: 'true' },
                { label: '未读', value: 'false' }
            ]
        },
        {
            name: 'dateRange',
            type: 'dateRange',
            placeholder: '创建时间'
        }
    ];

    // 获取对话记录列表
    const fetchRecords = async (params: ChatQueryParams = {}) => {
        setLoading(true);
        try {
            const queryParams = {
                page: pagination.current,
                limit: pagination.pageSize,
                ...searchParams,
                ...params,
            };

            const response: ChatApiResponse<ChatRecord> = await chatService.getChatList(queryParams);
            if (response.success && response.data) {
                setRecords(response.data.records || []);
                setPagination(prev => ({
                    ...prev,
                    current: response.data.pagination?.page || 1,
                    total: response.data.pagination?.total || 0,
                }));
            }
        } catch (error: any) {
            message.error(error?.message || '获取对话记录失败');
        } finally {
            setLoading(false);
        }
    };

    // 初始化
    useEffect(() => {
        fetchRecords();
    }, []);

    // 搜索
    const handleSearch = () => {
        const values = searchForm.getFieldsValue();
        const params: ChatQueryParams = {
            page: 1,
            limit: pagination.pageSize,
        };

        if (values.keyword) params.keyword = values.keyword;
        if (values.user_id) params.user_id = Number(values.user_id);
        if (values.room_id) params.room_id = values.room_id;
        if (values.message_type) params.message_type = values.message_type;
        if (values.is_read !== undefined) params.is_read = values.is_read === 'true';
        if (values.dateRange && values.dateRange.length === 2) {
            params.start_date = values.dateRange[0].format('YYYY-MM-DD');
            params.end_date = values.dateRange[1].format('YYYY-MM-DD');
        }

        setSearchParams(params);
        setPagination(prev => ({ ...prev, current: 1 }));
        fetchRecords(params);
    };

    // 重置搜索
    const handleResetSearch = () => {
        searchForm.resetFields();
        setSearchParams({});
        setPagination(prev => ({ ...prev, current: 1 }));
        fetchRecords({ page: 1, limit: pagination.pageSize });
    };

    // 分页变化
    const handlePaginationChange = (page: number, pageSize?: number) => {
        setPagination(prev => ({ ...prev, current: page, pageSize: pageSize || 20 }));
        fetchRecords({ ...searchParams, page, limit: pageSize || 20 });
    };

    // 查看详情
    const handleViewDetail = (record: ChatRecord) => {
        setCurrentRecord(record);
        setDetailModalVisible(true);
    };

    // 查看房间对话
    const handleViewRoom = async (roomId: string) => {
        try {
            setLoading(true);
            const records = await chatService.getRoomChatRecords(roomId);
            setRoomRecords(records);
            setRoomModalVisible(true);
        } catch (error: any) {
            message.error(error?.message || '获取房间对话失败');
        } finally {
            setLoading(false);
        }
    };

    // 删除记录
    const handleDelete = async (record: ChatRecord) => {
        try {
            await chatService.deleteChatRecord(record.id);
            message.success('删除成功');
            fetchRecords();
        } catch (error: any) {
            message.error(error?.message || '删除失败');
        }
    };

    // 删除房间对话
    const handleDeleteRoom = async (roomId: string) => {
        try {
            const result = await chatService.deleteRoomChatRecords(roomId);
            message.success(`删除成功，影响${result.deletedCount}条记录`);
            fetchRecords();
        } catch (error: any) {
            message.error(error?.message || '删除房间对话失败');
        }
    };

    // 批量删除
    const handleBatchDelete = async () => {
        if (selectedRowKeys.length === 0) {
            message.warning('请选择要删除的记录');
            return;
        }

        try {
            const result = await chatService.batchDeleteChatRecords(selectedRowKeys as number[]);
            message.success(`批量删除成功，影响${result.deletedCount}条记录`);
            setSelectedRowKeys([]);
            fetchRecords();
        } catch (error: any) {
            message.error(error?.message || '批量删除失败');
        }
    };

    // 清理过期记录
    const handleCleanupExpired = async () => {
        Modal.confirm({
            title: '清理过期记录',
            content: '确定要清理30天前的记录吗？此操作不可恢复。',
            onOk: async () => {
                try {
                    const result = await chatService.cleanupExpiredChatRecords(30);
                    message.success(`清理完成，删除了${result.deletedCount}条记录`);
                    fetchRecords();
                } catch (error: any) {
                    message.error(error?.message || '清理失败');
                }
            }
        });
    };

    // 切换已读状态
    const handleToggleReadStatus = async (record: ChatRecord) => {
        try {
            await chatService.updateChatReadStatus(record.id, !record.is_read);
            message.success(`标记为${!record.is_read ? '已读' : '未读'}成功`);
            fetchRecords();
        } catch (error: any) {
            message.error(error?.message || '更新状态失败');
        }
    };

    // 标记房间为已读
    const handleMarkRoomAsRead = async (roomId: string) => {
        try {
            const result = await chatService.markRoomMessagesAsRead(roomId);
            message.success(`成功标记${result.updatedCount}条消息为已读`);
            fetchRecords();
        } catch (error: any) {
            message.error(error?.message || '标记已读失败');
        }
    };

    // 表格列配置
    const columns: ColumnsType<ChatRecord> = [
        {
            title: '用户信息',
            key: 'userInfo',
            width: 150,
            render: (_, record) => (
                <div>
                    <div className="font-medium">
                        {record.username || `用户${record.user_id}`}
                    </div>
                    <div className="text-gray-500 text-sm">
                        ID: {record.user_id}
                    </div>
                </div>
            ),
        },
        {
            title: '房间ID',
            dataIndex: 'room_id',
            key: 'room_id',
            width: 160,
            render: (roomId) => (
                <Tooltip title="点击查看房间对话">
                    <Button
                        type="link"
                        size="small"
                        onClick={() => handleViewRoom(roomId)}
                    >
                        {roomId && roomId.length > 12 ? `${roomId.substring(0, 12)}...` : roomId || '-'}
                    </Button>
                </Tooltip>
            ),
        },
        {
            title: '消息类型',
            dataIndex: 'message_type',
            key: 'message_type',
            width: 100,
            render: (type) => (
                <Tag color={MESSAGE_TYPES[type as keyof typeof MESSAGE_TYPES]?.color}
                    icon={MESSAGE_TYPES[type as keyof typeof MESSAGE_TYPES]?.icon}>
                    {MESSAGE_TYPES[type as keyof typeof MESSAGE_TYPES]?.text}
                </Tag>
            ),
        },
        {
            title: '消息内容',
            dataIndex: 'message',
            key: 'message',
            render: (message) => (
                <Paragraph
                    ellipsis={{ rows: 2, expandable: true }}
                    style={{ marginBottom: 0, maxWidth: '300px' }}
                >
                    {message}
                </Paragraph>
            ),
        },
        {
            title: '是否已读',
            dataIndex: 'is_read',
            key: 'is_read',
            width: 100,
            render: (isRead) => (
                <Tag color={isRead ? 'green' : 'orange'} icon={isRead ? <CheckOutlined /> : <CloseOutlined />}>
                    {isRead ? '已读' : '未读'}
                </Tag>
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at',
            width: 150,
            render: (date) => dayjs(date).format('YYYY-MM-DD HH:mm'),
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            render: (_, record) => {
                const items: MenuProps['items'] = [
                    {
                        key: 'view',
                        icon: <EyeOutlined />,
                        label: '查看详情',
                        onClick: () => handleViewDetail(record),
                    },
                    {
                        key: 'room',
                        icon: <EyeOutlined />,
                        label: '查看房间对话',
                        onClick: () => handleViewRoom(record.room_id),
                    },
                    {
                        key: 'markRead',
                        icon: <CheckOutlined />,
                        label: '标记房间已读',
                        onClick: () => handleMarkRoomAsRead(record.room_id),
                    },
                    {
                        type: 'divider',
                    },
                    {
                        key: 'delete',
                        icon: <DeleteOutlined />,
                        label: '删除',
                        danger: true,
                        onClick: () => {
                            Modal.confirm({
                                title: '确认删除',
                                content: '确定要删除这条记录吗？',
                                onOk: () => handleDelete(record),
                            });
                        },
                    },
                    {
                        key: 'deleteRoom',
                        icon: <DeleteOutlined />,
                        label: '删除整个房间对话',
                        danger: true,
                        onClick: () => {
                            Modal.confirm({
                                title: '确认删除房间对话',
                                content: `确定要删除房间 "${record.room_id}" 的所有记录吗？`,
                                onOk: () => handleDeleteRoom(record.room_id),
                            });
                        },
                    },
                ];

                return (
                    <Dropdown menu={{ items }} placement="bottomRight">
                        <Button type="text" icon={<MoreOutlined />} />
                    </Dropdown>
                );
            },
        },
    ];

    // 工具栏动作配置
    const toolbarActions: ToolbarAction[] = [
        {
            key: 'cleanup',
            label: '清理过期记录',
            icon: <ClearOutlined />,
            onClick: handleCleanupExpired
        }
    ];

    // 批量操作配置
    const batchActions: BatchAction[] = [
        {
            key: 'delete',
            label: '批量删除',
            icon: <DeleteOutlined />,
            danger: true,
            onClick: () => {
                Modal.confirm({
                    title: '确认批量删除',
                    content: `确定要删除所选的 ${selectedRowKeys.length} 条记录吗？`,
                    onOk: handleBatchDelete,
                });
            },
        },
    ];

    return (
        <div className="space-y-6">
            {/* 搜索区域 */}
            <SearchForm
                fields={searchFields}
                form={searchForm}
                onSearch={handleSearch}
                onReset={handleResetSearch}
                loading={loading}
            />

            {/* 普通聊天记录列表 */}
            <DataTable<ChatRecord>
                title="普通聊天记录"
                columns={columns}
                dataSource={records}
                rowKey="id"
                loading={loading}
                pagination={{
                    ...pagination,
                    onChange: handlePaginationChange,
                }}
                rowSelection={{
                    selectedRowKeys,
                    onChange: setSelectedRowKeys,
                }}
                toolbarActions={toolbarActions}
                batchActions={batchActions}
                adaptiveHeight={true}
                scroll={{ x: 1200 }}
            />

            {/* 详情模态框 */}
            <Modal
                title="聊天记录详情"
                open={detailModalVisible}
                onCancel={() => {
                    setDetailModalVisible(false);
                    setCurrentRecord(null);
                }}
                footer={null}
                width={600}
            >
                {currentRecord && (
                    <div className="space-y-4">
                        <div>
                            <Text strong>用户：</Text>
                            <Text>{currentRecord.username || `用户${currentRecord.user_id}`}</Text>
                        </div>
                        <div>
                            <Text strong>房间ID：</Text>
                            <Text code>{currentRecord.room_id}</Text>
                        </div>
                        <div>
                            <Text strong>消息类型：</Text>
                            <Tag color={MESSAGE_TYPES[currentRecord.message_type as keyof typeof MESSAGE_TYPES]?.color}>
                                {MESSAGE_TYPES[currentRecord.message_type as keyof typeof MESSAGE_TYPES]?.text}
                            </Tag>
                        </div>
                        <div>
                            <Text strong>状态：</Text>
                            <Tag color={currentRecord.is_read ? 'green' : 'orange'}>
                                {currentRecord.is_read ? '已读' : '未读'}
                            </Tag>
                        </div>
                        <div>
                            <Text strong>创建时间：</Text>
                            <Text>{dayjs(currentRecord.created_at).format('YYYY-MM-DD HH:mm:ss')}</Text>
                        </div>
                        <div>
                            <Text strong>消息内容：</Text>
                            <div className="mt-2 p-3 bg-gray-50 rounded">
                                <Paragraph style={{ marginBottom: 0 }}>
                                    {currentRecord.message}
                                </Paragraph>
                            </div>
                        </div>
                    </div>
                )}
            </Modal>

            {/* 房间对话模态框 */}
            <Modal
                title="房间对话记录"
                open={roomModalVisible}
                onCancel={() => {
                    setRoomModalVisible(false);
                    setRoomRecords([]);
                }}
                footer={null}
                width={800}
            >
                <div className="max-h-96 overflow-y-auto space-y-3">
                    {roomRecords.map((record) => (
                        <div
                            key={record.id}
                            className={`p-3 rounded ${record.is_read
                                ? 'bg-gray-50'
                                : 'bg-orange-50 border-l-4 border-orange-400'
                                }`}
                        >
                            <div className="flex justify-between items-center mb-2">
                                <div className="flex items-center space-x-2">
                                    <Tag
                                        color={MESSAGE_TYPES[record.message_type as keyof typeof MESSAGE_TYPES]?.color}
                                        icon={MESSAGE_TYPES[record.message_type as keyof typeof MESSAGE_TYPES]?.icon}
                                    >
                                        {MESSAGE_TYPES[record.message_type as keyof typeof MESSAGE_TYPES]?.text}
                                    </Tag>
                                    <Text strong>{record.username || `用户${record.user_id}`}</Text>
                                    <Tag color={record.is_read ? 'green' : 'orange'}>
                                        {record.is_read ? '已读' : '未读'}
                                    </Tag>
                                </div>
                                <Text type="secondary" className="text-xs">
                                    {dayjs(record.created_at).format('HH:mm:ss')}
                                </Text>
                            </div>
                            <div>{record.message}</div>
                        </div>
                    ))}
                </div>
            </Modal>
        </div>
    );
};

export default NormalChatPage; 